package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.BaseException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.data.annotation.Id;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {
    @Resource
    private DishMapper dishMapper;
    @Resource
    private DishFlavorMapper dishFlavorMapper;
    @Resource
    private SetmealDishMapper setmealDishMapper;
    @Transactional
    public void saveWithFlavor(DishDTO dto) {
//        向菜品表插入一条数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto,dish);
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setCreateTime(LocalDateTime.now());
        dishMapper.insert(dish);

//        向口味表插入n条数据
        List<DishFlavor> flavors = dto.getFlavors();
        if (flavors==null||flavors.size()==0)
            return;
        flavors.forEach(v->{v.setDishId(dish.getId());});

        dishFlavorMapper.insert(flavors);

    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<DishVO> dishVOS = dishMapper.pageQuery(dto);
        PageResult result = new PageResult();
        result.setTotal(dishVOS.getTotal());
        result.setRecords(dishVOS.getResult());
        return result;
    }

    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        List<Dish> dishes = dishMapper.selectByIds(ids);

        //是否纯在正在起售的
        for (Dish dish : dishes) {
            if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE))
                throw new BaseException("正在起售的不允许删除");
        }

        //是否被套餐关联

        QueryWrapper<SetmealDish> wrapper = new QueryWrapper<>();

        wrapper.in("dish_id",ids);
        Long count = setmealDishMapper.selectCount(wrapper);
        if (count>0)
            throw new BaseException("当前菜品被套餐关联不能删除");

        //删除菜品表
        dishMapper.deleteByIds(ids);

        //删除关联的口味表
        QueryWrapper<DishFlavor> wrapper1 = new QueryWrapper<>();
        wrapper.in("dish_id",ids);
        dishFlavorMapper.delete(wrapper1);
    }

    @Override
    public DishVO getDish(Integer id) {
        Dish dish = dishMapper.getDish(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();
        wrapper.eq("dish_id",id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(wrapper);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    @Override
    @Transactional
    public void updateDish(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto,dish);
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());

        //删除旧数据
        QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();
        wrapper.eq("dish_id",dto.getId());
        dishFlavorMapper.delete(wrapper);


        List<DishFlavor> flavors = dto.getFlavors();
        flavors.forEach(v->v.setDishId(dto.getId()));

        dishFlavorMapper.insert(flavors);

        dishMapper.updateById(dish);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        UpdateWrapper<Dish> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",id).set("status",status);
        dishMapper.update(wrapper);
        //如果是停售将相关的套餐也停售
        if(status==StatusConstant.DISABLE){
            dishMapper.disableSetmeal(id);
        }
    }

    @Override
    public List<DishVO> getCategory(Long categoryId) {
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", categoryId);

        List<Dish> dishes = dishMapper.selectList(wrapper);
        List<DishVO> dishVOS = new ArrayList<>(dishes.size());
        for (Dish dish : dishes) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish,dishVO);
            dishVOS.add(dishVO);
        }

        return dishVOS;
    }


    @Override
    public List<DishVO> listWithFlavor(Long categoryId) {


        List<Dish> dishList = dishMapper.getDishByCategoryId(categoryId);
        if (dishList.size()==0)
            return Collections.emptyList();
        List<Long> ids= new ArrayList<>(dishList.size());
        List<DishVO> dishVOS= new ArrayList<>(dishList.size());
        //根据菜品id查询口味
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            ids.add(d.getId());
            dishVOS.add(dishVO);
        }
        QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();
        wrapper.in("dish_id",ids);
        List<DishFlavor> flavors = dishFlavorMapper.selectList(wrapper);
        if (flavors.size()==0)
            return dishVOS;
        for (DishVO d : dishVOS) {
            //根据菜品id查询对应的口味
            List<DishFlavor> dishFlavors = flavors.stream().filter(f -> Objects.equals(f.getDishId(), d.getId())).collect(Collectors.toList());
            d.setFlavors(dishFlavors);
        }

        return dishVOS;
    }
}
